from django.db import models
from django.db.models import Sum
from rest_framework.authtoken.models import Token
from apps.Basic_data.models import Product, Suppliers


class CommonFields(models.Model):
    """
    通用字段模型
    """
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    remark = models.TextField(verbose_name='备注', blank=True, null=True)
    # token = models.OneToOneField(Token, on_delete=models.CASCADE)

    class Meta:
        abstract = True


class PurchaseOrder(CommonFields):
    class DeliveryStatus(models.IntegerChoices):
        PENDING = 0, '待处理'
        IN_PROGRESS = 1, '进行中'
        DELIVERED = 2, '已发货'
        CANCELLED = 3, '已取消'
        COMPLETED = 4, '已完成'
        ON_HOLD = 5, '暂停'
        RETURNED = 6, '已退货'
        REJECTED = 7, '已拒绝'
        CREATED = 8, '已创建'
        UNKNOWN = 9, '未知'
        # 添加其他状态选项
    purchase_order_code = models.CharField(max_length=100, primary_key=True,  verbose_name="订单编号")
    vendor = models.ForeignKey(Suppliers, on_delete=models.CASCADE,  verbose_name="供应商")
    # order_status = models.CharField(max_length=100, help_text="订单状态", verbose_name="订单状态", default=None)
    order_status = models.IntegerField(choices=DeliveryStatus.choices,
                                       verbose_name="订单状态", default=DeliveryStatus.CREATED)
    order_total = models.DecimalField(max_digits=10, decimal_places=2, help_text="订单总价",
                                      default=0.00, verbose_name="订单总价",  blank=True, null=True)
    order_date = models.DateField(auto_created=True, verbose_name="订单日期")
    requested_delivery_date = models.DateField( default=None, verbose_name="要求交货日期",  blank=True, null=True)
    actual_delivery_date = models.DateField( default=None, verbose_name="实际交货日期",  blank=True, null=True)
    order_notes = models.TextField( default="", verbose_name='备注',  blank=True, null=True)

    class Meta:
        verbose_name = '采购订单'
        verbose_name_plural = '采购订单'

    def __str__(self):
        return self.purchase_order_code


class PurchaseOrderDetail(CommonFields):
    purchase_order_code = models.ForeignKey(PurchaseOrder, on_delete=models.CASCADE, help_text="采购订单号",
                                            verbose_name="采购订单号")
    status = models.BooleanField(default=True, verbose_name="状态")
    product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="产品")
    quantity = models.IntegerField(verbose_name="订单数量", default=0)
    has_received_quantities = models.IntegerField(verbose_name="已收数量", default=0)
    has_returned_quantities = models.IntegerField(verbose_name="已退数量", default=0)
    order_notes = models.TextField(help_text="订单备注", default=None, verbose_name='备注', null=True)

    @property
    def get_received_quantities(self):
        """已接收数量"""
        if PurchaseReceiptDetail.objects.filter(purchase_order_detail=self).exists():
            return PurchaseReceiptDetail.objects.filter(purchase_order_detail=self).aggregate(Sum('quantity_received'))[
                'quantity_received__sum']
        else:
            return 0

    @property
    def get_returned_quantities(self):
        """退货数量"""
        if PurchaseReturnDetail.objects.filter(purchase_order_detail=self).exists():
            return PurchaseReturnDetail.objects.filter(purchase_order_detail=self).aggregate(Sum('quantity_returned'))[
                'quantity_returned__sum']
        else:
            return 0

    @property
    def get_not_received_quantities(self):
        """未回数量"""
        return self.quantity - self.get_received_quantities - self.get_returned_quantities

    @property
    def get_product_name(self):
        """产品名称"""
        return self.product.name

    class Meta:
        verbose_name = '采购订单详情'
        verbose_name_plural = '采购订单详情'

    def __str__(self):
        string = "DT" + self.product.goods_id[2:]
        return f"{self.purchase_order_code}-{string}-{self.product.name}-{self.get_not_received_quantities}"


class PurchaseReceipt(CommonFields):
    class PurchaseReceiptStatus(models.IntegerChoices):
        PENDING = 0, '待处理'
        IN_PROGRESS = 1, '进行中'
        DELIVERED = 2, '已发货'
        CANCELLED = 3, '已取消'
        COMPLETED = 4, '已完成'
        ON_HOLD = 5, '暂停'
        RETURNED = 6, '已退货'
        REJECTED = 7, '已拒绝'
        CREATED = 8, '已创建'
        UNKNOWN = 9, '未知'
        # 添加其他状态选项

    class DeliveryStatus(models.IntegerChoices):
        PENDING = 0, '待处理'
        IN_PROGRESS = 1, '进行中'
        DELIVERED = 2, '已发货'
        CANCELLED = 3, '已取消'
        COMPLETED = 4, '已完成'
        ON_HOLD = 5, '暂停'
        RETURNED = 6, '已退货'
        REJECTED = 7, '已拒绝'
        CREATED = 8, '已创建'
        UNKNOWN = 9, '未知'
        # 添加其他状态选项
    purchase_receipt_code = models.CharField(max_length=100, primary_key=True, help_text="入库编号",
                                             verbose_name="入库编号")
    receipt_date = models.DateField(help_text="入库日期", auto_now=True, verbose_name="入库日期")
    status = models.IntegerField(choices=PurchaseReceiptStatus, help_text="入库状态", verbose_name="入库状态",
                                 default=PurchaseReceiptStatus.UNKNOWN)
    total_quantity = models.IntegerField(help_text="总数量", default=0, verbose_name="总数量")
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, help_text="总金额", default=0.00,
                                       verbose_name="总金额")
    vendor = models.ForeignKey(Suppliers, on_delete=models.CASCADE, help_text="供应商", verbose_name="供应商")
    order_date = models.DateField(help_text="订单日期", default=None, verbose_name="订单日期")
    requested_delivery_date = models.DateField(auto_now=True, help_text="要求交货日期",
                                               verbose_name="要求交货日期", null=True)
    actual_delivery_date = models.DateField(help_text="实际交货日期", auto_now=True,
                                            verbose_name="实际交货日期")
    order_status = models.IntegerField(choices=DeliveryStatus.choices,
                                       help_text="订单状态", verbose_name="订单状态", default=DeliveryStatus.CREATED)
    order_details = models.ManyToManyField(PurchaseOrderDetail, through='PurchaseReceiptDetail', verbose_name="订单详情")
    notes = models.TextField(help_text="备注", default="", verbose_name='备注', blank=True)

    class Meta:
        verbose_name = '采购入库单'
        verbose_name_plural = '采购入库单'

    def __str__(self):
        return self.purchase_receipt_code


class PurchaseReceiptDetail(CommonFields):
    purchase_receipt_code = models.ForeignKey(PurchaseReceipt, on_delete=models.CASCADE,
                                              help_text="入库编号", verbose_name="入库订单")
    purchase_order_detail = models.ForeignKey(PurchaseOrderDetail, on_delete=models.CASCADE, help_text="采购订单详情",
                                              verbose_name="采购订单详情")
    quantity_received = models.IntegerField(help_text="接收数量", verbose_name='接受数量')

    class Meta:
        verbose_name = '采购入库单详情'
        verbose_name_plural = '采购入库单详情'

    def __str__(self):
        return f"{self.purchase_receipt_code} - {self.purchase_order_detail}"


class PurchaseReturn(CommonFields):
    class PurchaseReturnStatus(models.IntegerChoices):
        PENDING = 0, '待处理'
        IN_PROGRESS = 1, '进行中'
        DELIVERED = 2, '已发货'
        CANCELLED = 3, '已取消'
        COMPLETED = 4, '已完成'
        ON_HOLD = 5, '暂停'
        RETURNED = 6, '已退货'
        REJECTED = 7, '已拒绝'
        CREATED = 8, '已创建'
        UNKNOWN = 9, '未知'
    purchase_return_code = models.CharField(max_length=100, primary_key=True, verbose_name="退货单号")
    return_date = models.DateField(help_text="退货日期", verbose_name="退货日期", auto_now_add=True)
    vendor = models.ForeignKey(Suppliers, on_delete=models.CASCADE, verbose_name="供应商")
    status = models.IntegerField(choices=PurchaseReturnStatus, verbose_name="退货状态")
    order_details = models.ManyToManyField(PurchaseOrderDetail, through='PurchaseReturnDetail', verbose_name='订单详情')

    class Meta:
        verbose_name = '采购退货单'
        verbose_name_plural = '采购退货单'

    def __str__(self):
        return self.purchase_return_code


class PurchaseReturnDetail(CommonFields):
    purchase_return_code = models.ForeignKey(PurchaseReturn, on_delete=models.CASCADE, help_text="退货单号",
                                             verbose_name="退货单号")
    purchase_order_detail = models.ForeignKey(PurchaseOrderDetail, on_delete=models.CASCADE, help_text="采购订单详情",
                                              verbose_name="采购订单详情")
    quantity_returned = models.IntegerField(help_text="退货数量", verbose_name="退货数量")
    reason = models.TextField(help_text='退货原因', verbose_name='退货原因')

    class Meta:
        verbose_name = '采购退货单详情'
        verbose_name_plural = '采购退货单详情'

    def __str__(self):
        return f"{self.purchase_return_code} - {self.purchase_order_detail}"
